package eteam.aps.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import eteam.aps.api.U8Api;
import eteam.aps.common.R;
import eteam.aps.common.constant.ProductType;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Assert;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JsonPage;
import eteam.aps.model.dto.SaleDto;
import eteam.aps.model.dto.SaleQueryDto;
import eteam.aps.model.entity.InvCode;
import eteam.aps.model.entity.other.Customer;
import eteam.aps.model.entity.sale.SaleOrder;
import eteam.aps.model.export.KV;
import eteam.aps.model.vo.product_number.ProductNumberOrderVo;
import eteam.aps.model.vo.sale.SaleOrderDetailsVo;
import eteam.aps.model.vo.sale.SaleOrderScanDto;
import eteam.aps.model.vo.sale.SaleOrderVo;
import eteam.aps.service.SaleOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售单 前端控制器
 *
 * @author Ll
 * @since 2024/01/09
 */
@Api(tags = "销售单相关接口")
@RestController
@RequestMapping("so")
@AllArgsConstructor
public class SaleOrderController {

    private final SaleOrderService saleOrderService;

    @ApiOperation("条件查询销售单信息")
    @PostMapping("page")
    public R<JsonPage<SaleOrderVo>> selectPage(@RequestBody SaleQueryDto query) {
        Map<String, Object> map = new HashMap<>();
        map.put("state", ParentEntity.FSTATE_DELETED);
        if (Helper.isNotEmpty(query.getOrderNumber())) {
            map.put("orderNumber", Helper.likeSql(query.getOrderNumber()));
        }
        if (Helper.isNotEmpty(query.getCustomerCode())) {
            map.put("customerCode", query.getCustomerCode());
        }
        if (Helper.isNotEmpty(query.getHandlerPeople())) {
            map.put("handlerPeople", Helper.likeSql(query.getHandlerPeople()));
        }
        if (Helper.isNotEmpty(query.getLogisticsCode())) {
            map.put("logisticsCode", Helper.likeSql(query.getLogisticsCode()));
        }
        if (query.getStartTime() != null) {
            map.put("startTime", query.getStartTime());
        }
        if (query.getEndTime() != null) {
            map.put("endTime", query.getEndTime());
        }
        return R.success(saleOrderService.selectPage(map, query.getPage(), query.getSize()));
    }

    @ApiOperation("查询销售单物料信息")
    @PostMapping("od")
    @ApiImplicitParam(name = "order", value = "销售单单号")
    public R<List<SaleOrderDetailsVo>> selectOrderDetails(String order) {
        Assert.isEmpty(order, "请选择销售单！");
        return R.success(saleOrderService.selectOrderDetails(order));
    }

//    @ApiOperation("查询销售产品销售信息")
//    @PostMapping("odb")
//    @ApiImplicitParam(name = "orderDetailId", value = "销售单物料详情Id")
//    public R<List<SaleAlreadyVo>> selectPage(String orderDetailId) {
//        Assert.isEmpty(orderDetailId, "请选择销售单详情！");
//        return R.success(saleOrderService.selectOrderProductDetails(orderDetailId));
//    }

    @ApiOperation("查询销售产品销售信息")
    @PostMapping("odb")
    public R<List<KV<String, String>>> selectPage(@RequestBody SaleOrderScanDto scan) {
        Assert.isBlank(scan.getfSaleOrderCode(), "订单编号不能为空！");
        Assert.isTrue(scan.getfSeqNo() < 0, "请输入有效的行号！");
        return R.success(saleOrderService.selectOrderProductDetails(scan));
    }

    /**
     * @since 2025/05/20
     */
    @ApiOperation("撤销")
    @PostMapping("cancel")
    public R<Void> cancel(@RequestBody SaleOrderScanDto scan) throws Exception {
        Assert.isBlank(scan.getfBarCode(), "条码id不能为空！");
        Assert.isBlank(scan.getfSaleOrderCode(), "订单编号不能为空！");
        Assert.isEmpty(scan.getfSeqNo(), "请输入有效的行号！");
        saleOrderService.cancelOrder(scan);
        return R.success();
    }

    @ApiOperation("查询物料库存信息")
    @PostMapping("stock")
    @ApiImplicitParam(name = "invCode", value = "物料编号")
    public R<List<ProductNumberOrderVo>> selectOrderInvProduct(String invCode) {
        Assert.isEmpty(invCode, "请选择销物料信息！");
        Map<String, Object> map = new HashMap<>();
        map.put("invCode", invCode);
        map.put("type", ProductType.STORAGE);
        map.put("state", ParentEntity.FSTATE_DELETED);
        return R.success(saleOrderService.selectOrderInvProduct(map));
    }


    @ApiOperation("删除销售订单")
    @PostMapping("de")
    @ApiImplicitParam(name = "fId", value = "销售单编号")
    public R<Void> deleteSaleOrder(String fId) throws Exception {
        Assert.isEmpty(fId, "请选择销售单编号！");
        saleOrderService.deleteSaleOrder(fId);
        return R.success();
    }

    @ApiOperation("添加一张销售订单")
    @PostMapping("save")
    public R<Void> save(@RequestBody SaleDto sale) throws Exception {
        if (sale == null || sale.getSale() == null) throw new BusinessException("销售单不能为空！");
        SaleOrder order = sale.getSale();
//        Assert.isBlank(order.getfCustomerCode(), "顾客编号不能为空！");
//        Assert.isBlank(order.getfCustomerName(), "顾客名称不能为空！");
        Assert.isBlank(order.getfHandlerName(), "经办人不能为空！");
        Assert.isBlank(order.getfHandlerPhone(), "经办人电话不能为空！");
        Assert.isEmpty(order.getfSendDate(), "发货时间不能为空！");
//        Assert.isBlank(order.getfLogisticsCode(), "物流单号不能为空！");
//        Assert.isBlank(order.getfLogisticsName(), "物流名称不能为空！");
//        Assert.isBlank(order.getfSendLogistics(), "发货物流不能为空！");
        Assert.isBlank(order.getfShipper(), "发货方不能为空！");
        Assert.isBlank(order.getfShipperPeople(), "发货人不能为空！");
        Assert.isBlank(order.getfShipperPhone(), "发货人电话不能为空！");
        Assert.isBlank(order.getfSendAddress(), "发货地址不能为空！");
        Assert.isBlank(order.getfShipper(), "收货方不能为空！");
        Assert.isBlank(order.getfReceivePeople(), "收货人不能为空！");
        Assert.isBlank(order.getfReceivePhone(), "收货人电话不能为空！");
        Assert.isBlank(order.getfReceiveAddress(), "收货地址不能为空！");
        sale.getSaleBil().forEach(data -> {
            Assert.isBlank(data.getfInvCode(), "物料编号不能为空！");
            Assert.isTrue(data.getfSendNum().compareTo(BigDecimal.ZERO) <= 0, "发货数不能为空！");
        });
        saleOrderService.saveOrder(sale);
        return R.success();
    }

    @ApiOperation("修改销售订单")
    @PostMapping("update")
    public R<Void> update(@RequestBody SaleOrder order) throws Exception {
        if (order == null) throw new BusinessException("销售单不能为空！");
        Assert.isEmpty(order.getfId(), "销售单内码不能为空！");
//        Assert.isEmpty(order.getfSendDate(), "发货时间不能为空！");
        Assert.isBlank(order.getfLogisticsCode(), "物流单号不能为空！");
        Assert.isBlank(order.getfLogisticsName(), "物流名称不能为空！");
        Assert.isBlank(order.getfSendLogistics(), "发货物流不能为空！");
        saleOrderService.updateSaleOrder(order);
        return R.success();
    }

    @ApiOperation("查询订单物料对应的库存")
    @PostMapping("ssb")
    @ApiImplicitParam(name = "invCode", value = "物料编号")
    public R<List<ProductNumberOrderVo>> selectSaleBar(String invCode) {
        Assert.isBlank(invCode, "请选择要发货的物料");
        Map<String, Object> map = new HashMap<>();
        map.put("state", ParentEntity.FSTATE_DELETED);
        map.put("type", ProductType.STORAGE);
        map.put("invCode", invCode);
        List<ProductNumberOrderVo> list = saleOrderService.selectSaleBar(map);
        Assert.isTrue(list.isEmpty(), "暂无库存数据！");
        return R.success(list);
    }

    @ApiOperation("选择订单入库信息")
    @PostMapping("cfb")
    public R<Void> confirmSaleBar(@RequestBody eteam.aps.model.dto.SaleScanDto scan) throws Exception {
        Assert.isBlank(scan.getOrderNumber(), "请选择发货单");
        Assert.isBlank(scan.getInvCode(), "请选择要发货的物料");
        Assert.isTrue(scan.getBar() != null && scan.getBar().isEmpty(), "请选择要发货的产品");
        saleOrderService.confirmSaleBar(scan);
        return R.success();
    }

    @PostMapping("/gc")
    @ApiOperation("获取所有的客户信息")
    public R<List<Customer>> getCustomer() throws Exception {
        List<Customer> customer = U8Api.getCustomer();
        if (customer.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "暂无数据！");
        return R.success(customer);
    }

    @PostMapping("inv")
    @ApiOperation("根据物料编号查询物料信息")
    @ApiImplicitParam(name = "invCode", value = "物料编号")
    public R<InvCode> getInvByInvCode(String invCode) throws JsonProcessingException {
        if (Helper.isEmpty(invCode)) throw new BusinessException(HttpStatus.BAD_REQUEST, "物料编号不能为空！");
        List<InvCode> code = U8Api.getInvByInvCode(invCode);
        if (code.isEmpty()) throw new BusinessException("暂无物料信息");
        return R.success(code.get(0));
    }

    @PostMapping("invs")
    @ApiOperation("根据物料编号查询物料信息")
    @ApiImplicitParam(name = "invCode", value = "物料编号")
    public R<List<InvCode>> getInvByInvCode(@RequestBody List<String> invCode) throws JsonProcessingException {
        if (invCode.isEmpty()) throw new BusinessException(HttpStatus.BAD_REQUEST, "物料编号不能为空！");
        List<InvCode> code = U8Api.getInvByInvCode(invCode);
        if (code.isEmpty()) throw new BusinessException("暂无物料信息");
        code.sort(Comparator.comparingInt(a -> invCode.indexOf(a.getInvCode())));
        return R.success(code);
    }
}
